{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 神经网络，感知机\n",
    "from sklearn.datasets import load_digits # 导入手写数字数据集\n",
    "from sklearn.model_selection import train_test_split # 导入数据集划分函数  \n",
    "from sklearn.neural_network import MLPClassifier # 导入多层感知机分类器\n",
    "from sklearn.metrics import accuracy_score # 导入准确率计算函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[ 0.,  0.,  5., ...,  0.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ..., 10.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ..., 16.,  9.,  0.],\n",
       "        ...,\n",
       "        [ 0.,  0.,  1., ...,  6.,  0.,  0.],\n",
       "        [ 0.,  0.,  2., ..., 12.,  0.,  0.],\n",
       "        [ 0.,  0., 10., ..., 12.,  1.,  0.]]),\n",
       " array([0, 1, 2, ..., 8, 9, 8]),\n",
       " (1797, 64),\n",
       " (1797,),\n",
       " (1797, 8, 8))"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = load_digits() # 加载手写数字数据集\n",
    "X = data.images.reshape(len(data.images), -1) # 将图像数据展平为二维数组\n",
    "y = data.target # 目标标签\n",
    "X, y, X.shape, y.shape, data.images.shape # 输出特征数据和目标标签的形状,并检验形状"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9796296296296296"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 划分训练集和测试集,第一个参数是特征数据，第二个参数是目标标签，test_size=0.3表示30%的数据用于测试集，其余70%用于训练集\n",
    "model = model = MLPClassifier(hidden_layer_sizes=(100,), max_iter=300) # 创建多层感知机模型，hidden_layer_sizes指定隐藏层的神经元数量，max_iter指定最大迭代次数,相当于深度学习的epoch\n",
    "model.fit(X_train, y_train) # 训练模型\n",
    "y_pred = model.predict(X_test) # 预测测试集\n",
    "accuracy = accuracy_score(y_test, y_pred) # 计算准确率\n",
    "accuracy # 输出准确率"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
